<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="null">
    <meta name="keyword" content="null">
    <meta name="theme-color" content="#600090">
    <meta name="msapplication-navbutton-color" content="#600090">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#600090">
    <link rel="shortcut icon" href="/assets/favicon.ico">
    <link rel="alternate" type="application/atom+xml" title="张小阳" href="/atom.xml">
    <link rel="stylesheet" href="https://cdn.bootcss.com/animate.css/3.5.2/animate.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.css">
    <title>
        
        Promise｜MillZhang&#39;s blog
        
    </title>

    <link rel="canonical" href="http://millzhang.github.io/2017/07/03/2017-note/23.Promise/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/blog-style.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">
</head>

<!-- hack iOS CSS :active style -->
<body ontouchstart="" class="animated fadeIn">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top " id="nav-top" data-ispost = "true" data-istags="false
" data-ishome = "false" >
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand animated pulse" href="/">
                <span class="brand-logo">
                    MillZhang
                </span>
            </a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <!-- /.navbar-collapse -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/"><i class="fa fa-home"></i>主页</a>
                    </li>
                   <li>
                        <a href="/tags"><i class="fa fa-tags"></i>归档</a>
                    </li>
                    <li>
                        <a href="/about"><i class="fa fa-user"></i>关于</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
//    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>

<!-- Main Content -->

<!--only post-->

<header class="intro-header">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <div class="post-heading">
                    <h1>Promise</h1>
                    
                    <span class="meta">
                         作者 MillZhang
                        <span>
                          日期 2017-07-03
                         </span>
                    </span>
                    <div class="tags text-center">
                        
                        <a class="tag" href="/tags/#javascript"
                           title="javascript">javascript</a>
                        
                        <a class="tag" href="/tags/#unfinished"
                           title="unfinished">unfinished</a>
                        
                        <a class="tag" href="/tags/#es6"
                           title="es6">es6</a>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="post-title-haojen">
        <span>
            Promise
        </span>
    </div>
    <div class="post-header-image">
        
            <img src="http://oritfw5nq.bkt.clouddn.com/wall-303.jpg?imageView2/0/format/jpg/interlace/1/q/85|watermark/2/text/QnkgTWlsbHpoYW5n/font/5b6u6L2v6ZuF6buR/fontsize/480/fill/I0ZERkRGRA==/dissolve/56/gravity/SouthEast/dx/10/dy/10|imageslim">
         
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">
            <!-- Post Container -->
            <div class="col-lg-8 col-lg-offset-1 col-sm-9 post-container">
                <h3 id="含义"><a href="#含义" class="headerlink" title="含义"></a>含义</h3><p><code>Promise</code>是异步编程的一种解决方案,相比较传统的回调函数和事件更合理,功能更强大.<br><code>Promise</code>,本质上就是一个容器,里面保存着某个未来才会结束的事件(常是一个异步操作).语法上,<code>Promise</code>是一个对象,可以获取异步操作的消息.</p>
<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><ul>
<li><strong>对象的状态不受外界影响</strong>.<code>Promise</code>对象有三种状态,<code>pending</code>(进行中),<code>resolved</code>(已完成),<code>rejected</code>(已失败).</li>
<li><strong>一旦状态改变，就不会再变.</strong><code>Promise</code>在状态切换过程中,是永久的,一旦状态改变了,任何时候去获取该状态是不会变的.也是会立即得到该结果.</li>
</ul>
<h3 id="Promise实例"><a href="#Promise实例" class="headerlink" title="Promise实例"></a><code>Promise</code>实例</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</div><div class="line">  <span class="keyword">if</span>(<span class="comment">/*异步操作*/</span>)&#123;</div><div class="line">    resolve(value);</div><div class="line">  &#125;<span class="keyword">else</span>&#123;</div><div class="line">    reject(error);</div><div class="line">  &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p><code>Promise</code>实例生成后,可以用<code>then</code>方法分别指定<code>resolved</code>和<code>rejected</code>状态的回调:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">promise.then(<span class="function"><span class="params">value</span>=&gt;</span>&#123;</div><div class="line">    <span class="comment">//success</span></div><div class="line">&#125;,error=&gt;&#123;</div><div class="line">    <span class="comment">//failure</span></div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p><code>then</code>方法结束两个参数,第一个<code>resolved</code>调用,第二个<code>rejected</code>调用,其中第二个参数不是必须的.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//简单实例</span></div><div class="line"><span class="keyword">let</span> timeout = <span class="function"><span class="keyword">function</span>(<span class="params">ms</span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</div><div class="line">        setTimeout(resolve,ms,<span class="string">'run over'</span>);</div><div class="line">    &#125;);</div><div class="line">&#125;</div><div class="line"></div><div class="line">timeout(<span class="number">1000</span>).then(<span class="function"><span class="params">value</span>=&gt;</span>&#123;</div><div class="line">    <span class="built_in">console</span>.log(value);</div><div class="line">&#125;)</div><div class="line"></div><div class="line"><span class="comment">//图片加载</span></div><div class="line"><span class="keyword">let</span> afterImageLoaded = <span class="function"><span class="keyword">function</span>(<span class="params">url</span>)</span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</div><div class="line">        <span class="keyword">let</span> image = <span class="keyword">new</span> Image();</div><div class="line">        image.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">            resolve(image.src);</div><div class="line">        &#125;</div><div class="line">        </div><div class="line">        image.onerror = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">            reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'cannot load image through by url:'</span>+ url));</div><div class="line">        &#125;</div><div class="line">        </div><div class="line">        image.src = url;</div><div class="line">    &#125;);</div><div class="line">&#125;</div><div class="line"></div><div class="line">afterImageLoaded(<span class="string">`http://oritfw5nq.bkt.clouddn.com/wall-303.jpg`</span>).then(<span class="function"><span class="params">value</span>=&gt;</span>&#123;</div><div class="line">    <span class="built_in">console</span>.log(value)</div><div class="line">&#125;,error=&gt;&#123;</div><div class="line">    <span class="built_in">console</span>.error(error);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<blockquote>
<p><a href="https://jsbin.com/yepotuc/edit?js,console" target="_blank" rel="external">https://jsbin.com/yepotuc/edit?js,console</a></p>
</blockquote>
<h3 id="Promise-prototype-then"><a href="#Promise-prototype-then" class="headerlink" title="Promise.prototype.then()"></a><code>Promise.prototype.then()</code></h3><p><code>then</code>方法的作用是为<code>Promise</code>实例添加状态改变时的回调函数.</p>
<p><code>then</code>方法返回的是一个新的<code>Promise</code>实例,因此可以采用链式的写法.</p>
<h3 id="Promise-prototype-catch"><a href="#Promise-prototype-catch" class="headerlink" title="Promise.prototype.catch()"></a><code>Promise.prototype.catch()</code></h3><blockquote>
<p><code>Promise.prototype.catch</code>方法是<code>.then(null, rejection)</code>的别名，用于指定发生错误时的回调函数。</p>
</blockquote>
<p>相比较而言,<code>reject</code>的作用就是向外抛出错误</p>
<p>如果Promise状态已经变成Resolved，再抛出错误是无效的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</div><div class="line">  resolve(<span class="string">'ok'</span>);</div><div class="line">  <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'test'</span>);</div><div class="line">&#125;);</div><div class="line">promise</div><div class="line">  .then(<span class="function"><span class="keyword">function</span>(<span class="params">value</span>) </span>&#123; <span class="built_in">console</span>.log(value) &#125;)</div><div class="line">  .catch(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123; <span class="built_in">console</span>.log(error) &#125;);</div><div class="line"><span class="comment">// ok</span></div></pre></td></tr></table></figure>
<p>上面代码中，<code>Promise</code>在<code>resolve</code>语句后面，再抛出错误，不会被捕获，等于没有抛出。因为<code>Promise</code>的状态一旦改变，就永久保持该状态，不会再变了。</p>
<p><code>Promise</code>对象的错误具有“冒泡”性质，会一直向后传递，直到被捕获为止。也就是说，错误总是会被下一个<code>catch</code>语句捕获。</p>
<h3 id="Promise-all"><a href="#Promise-all" class="headerlink" title="Promise.all()"></a><code>Promise.all()</code></h3><blockquote>
<p><code>Promise.all</code>方法用于将多个 <code>Promise</code> 实例，包装成一个新的 <code>Promise</code> 实例。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.all([p1, p2, p3]);</div></pre></td></tr></table></figure>
<h3 id="Promise-race"><a href="#Promise-race" class="headerlink" title="Promise.race()"></a><code>Promise.race()</code></h3><blockquote>
<p><code>Promise.race</code>方法同样是将多个Promise实例,包装成一个新的Promise实例</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.race([p1,p2,p3]);</div></pre></td></tr></table></figure>
                <hr>
                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2017/07/04/2017-note/24.ES6的编程风格/" data-toggle="tooltip" data-placement="top"
                           title="ES6编程风格摘要">&larr; 上一页</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/06/29/2017-note/22.getComputedStyle/" data-toggle="tooltip" data-placement="top"
                           title="getComputedStyle">下一页 &rarr;</a>
                    </li>
                    
                </ul>
                <div class="comment">
                    <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
                </div>
            </div>
            <div class="hidden-xs col-sm-3 toc-col">
                <div class="toc-wrap">
                    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#含义"><span class="toc-text">含义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#特点"><span class="toc-text">特点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise实例"><span class="toc-text">Promise实例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-prototype-then"><span class="toc-text">Promise.prototype.then()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-prototype-catch"><span class="toc-text">Promise.prototype.catch()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-all"><span class="toc-text">Promise.all()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-race"><span class="toc-text">Promise.race()</span></a></li></ol>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                

                <!-- Friends Blog -->
                
            </div>
        </div>

    </div>
</article>
<!-- 网易云音乐-->

<iframe class="cloud-music" frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 
    src="//music.163.com/outchain/player?type=2&amp;id=18803411&amp;auto=0&amp;height=66">
</iframe>
<!-- 网易云跟帖-->
<script src="https://img1.cache.netease.com/f2e/tie/yun/sdk/loader.js"></script>
<script>
var cloudTieConfig = {
  url: document.location.href, 
  sourceId: "",
  productKey: "40a8ee22b6084862a8907e6902e525fa",
  target: "cloud-tie-wrapper"
};
var yunManualLoad = true;
Tie.loader("aHR0cHM6Ly9hcGkuZ2VudGllLjE2My5jb20vcGMvbGl2ZXNjcmlwdC5odG1s", true);
</script>

<!-- Footer -->
<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <p class="copyright text-muted">
                    Copyright &copy; MillZhang 2017
                    <br>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/blog.js"></script>

<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://oritfw5nq.bkt.clouddn.com/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>



<!--wechat title img-->
<img class="wechat-title-img" src="http://oritfw5nq.bkt.clouddn.com/avatar.jpg?imageslim">
<a id="backtop" class="border-bottom" href="javascript:;">回顶部</a>
<script type="application/javascript">
var docOuter = document.body.scrollTop ? document.body : document.documentElement;
var backToTop = function(rate) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  var top = function() {
    scrollTop = scrollTop + (0 - scrollTop) / (rate || 2);
    if (scrollTop < 1) {
      doc.scrollTop = 0;
      return;
    }
    doc.scrollTop = scrollTop;
    // 动画gogogo!
    requestAnimationFrame(top);
  };
  top();
};
var topBtn = document.getElementById('backtop'),
    docTop = docOuter.scrollTop;
if(docTop>=300){
  topBtn.style.opacity = 1;
}

topBtn.onclick = function() {
  backToTop(12)
}
window.onscroll = function(e) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  if (scrollTop >= 300) {
    topBtn.style.opacity = 1;
  } else {
    topBtn.style.opacity = 0;
  }
}
</script>
</body>

</html>
